package wei.zhang.algorithm;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.math.BigInteger;
import java.util.Collection;

/**
 * 自定义分库
 */
public class RreciseDSShardingAlgorithm implements PreciseShardingAlgorithm<Long> {


    /**
     *
     * @param availableTargetNames  配置库 m1,m2
     * @param preciseShardingValue
     * @return
     */
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Long> preciseShardingValue) {

        //逻辑表
        String logicTableName = preciseShardingValue.getLogicTableName();
        //分表字段
        String id = preciseShardingValue.getColumnName();
        // 分表字段值
        Long value = preciseShardingValue.getValue();

        BigInteger bigInteger = BigInteger.valueOf(value);
        // value%2 +1;
        BigInteger result = (bigInteger.mod(new BigInteger("2"))).add(new BigInteger("1"));
        String key = "m"+ result;
        if (availableTargetNames.contains(key)) {
            return key;
        }
        throw new UnsupportedOperationException("datasource route " + key + " is not support please check your config");
    }
}
